<template>
  <div class="grade-wrap">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-fa fa-edit"></i> 成绩录入
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 统计卡片区域 -->
    <div class="statistics-area">
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-data-line"></i>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ averageScore.toFixed(1) }}</div>
          <div class="stat-label">平均成绩</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background-color: #67C23A;">
          <i class="el-icon-trophy"></i>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ excellentRate }}%</div>
          <div class="stat-label">优秀率</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background-color: #F56C6C;">
          <i class="el-icon-warning"></i>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ failRate }}%</div>
          <div class="stat-label">不及格率</div>
        </div>
      </div>
    </div>

    <div class="grade-container">
      <!-- 标题和状态提示 -->
      <div class="grade-header">
        <h3><i class="el-icon-edit-outline"></i> 学生成绩管理</h3>
        <div class="grade-status" v-if="!isButtonDisabled">
          <el-tag type="success">成绩录入开放中</el-tag>
        </div>
        <div class="grade-status" v-else>
          <el-tag type="info">成绩录入已关闭</el-tag>
        </div>
      </div>

      <!-- 搜索区域 -->
      <div class="query-form">
        <el-row :gutter="20">
          <el-col :span="7">
            <el-input
              @keyup.enter.native="query"
              placeholder="课程名称"
              prefix-icon="el-icon-reading"
              v-model="queryForm.courseName"
              clearable
            />
          </el-col>
          <el-col :span="7">
            <el-input
              @keyup.enter.native="query"
              placeholder="学生姓名"
              prefix-icon="el-icon-user"
              v-model="queryForm.studentName"
              clearable
            />
          </el-col>
          <el-col :span="3">
            <el-button @click="query" icon="el-icon-search" type="primary" class="search-btn">
              搜索
            </el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 数据表格 -->
      <div class="grade-table">
        <el-table :data="tableData" stripe border highlight-current-row>
          <el-table-column align="center" label="选课Id" prop="studentCourseId" width="100" />
          <el-table-column label="课程名称" prop="courseName" min-width="180" />
          <el-table-column label="学生姓名" prop="studentName" width="120" />
          <el-table-column align="center" label="日常分" width="100">
            <template slot-scope="scope">
              <span :class="getScoreClass(scope.row.dailyScore)">{{ scope.row.dailyScore || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="笔试分" width="100">
            <template slot-scope="scope">
              <span :class="getScoreClass(scope.row.examScore)">{{ scope.row.examScore || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="总成绩" width="100">
            <template slot-scope="scope">
              <el-tag :type="getScoreTagType(scope.row.score)" size="medium" effect="light">
                {{ scope.row.score || '-' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="120">
            <template slot-scope="scope">
              <el-button
                @click="edit(scope.row.studentCourseId)"
                size="mini"
                type="success"
                :disabled="isButtonDisabled"
                icon="el-icon-edit"
                circle
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page.sync="pageIndex"
          :page-size="pageSize"
          :total="pageSize * pageCount"
          @current-change="getPage"
          background
          layout="total, prev, pager, next, jumper"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog :visible.sync="editing" title="成绩录入" width="500px" custom-class="grade-dialog">
      <div class="dialog-content">
        <div class="dialog-header" v-if="entityForm.courseName">
          <div class="course-info">
            <h4>{{ entityForm.courseName }}</h4>
            <p v-if="entityForm.studentName">学生: {{ entityForm.studentName }}</p>
          </div>
        </div>
        <el-form :model="entityForm" label-width="120px" ref="form" status-icon>
          <el-form-item label="选课Id">
            <el-input
              disabled
              type="number"
              v-model="entityForm.studentCourseId"
              placeholder="系统自动生成"
            ></el-input>
          </el-form-item>
          <el-form-item label="日常成绩">
            <el-input-number 
              v-model="entityForm.dailyScore" 
              :min="0" 
              :max="100" 
              controls-position="right"
              placeholder="请输入日常成绩"
            ></el-input-number>
            <div class="score-tip">占比: 40%</div>
          </el-form-item>
          <el-form-item label="笔试成绩">
            <el-input-number 
              v-model="entityForm.examScore" 
              :min="0" 
              :max="100" 
              controls-position="right"
              placeholder="请输入笔试成绩"
            ></el-input-number>
            <div class="score-tip">占比: 60%</div>
          </el-form-item>
          <el-form-item label="总成绩">
            <el-input-number 
              v-model="entityForm.score" 
              :min="0" 
              :max="100" 
              controls-position="right"
              placeholder="请输入总成绩"
            ></el-input-number>
            <div class="score-tip">
              <el-button type="text" size="mini" @click="calculateFinalScore">
                <i class="el-icon-refresh"></i> 自动计算
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <span class="dialog-footer" slot="footer">
        <el-button @click="save" type="primary" icon="el-icon-check">保存</el-button>
        <el-button @click="editing = false" icon="el-icon-close">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as api from "../../api/teacher/grade";
import * as OptionApi from "@/api/option";

export default {
  name: "TeacherGrade",
  data() {
    return {
      queryForm: {
        courseName: "",
        studentName: ""
      },
      entityForm: {
        studentCourseId: null,
        dailyScore: null,
        examScore: null,
        score: null,
        courseName: '',
        studentName: ''
      },
      tableData: [],
      pageSize: api.pageSize,
      pageCount: 1,
      pageIndex: 1,
      editing: false,
      isButtonDisabled: true
    };
  },
  computed: {
    averageScore() {
      if (!this.tableData || this.tableData.length === 0) return 0;
      const total = this.tableData.reduce((sum, item) => {
        return sum + (parseFloat(item.score) || 0);
      }, 0);
      return total / this.tableData.length;
    },
    excellentRate() {
      if (!this.tableData || this.tableData.length === 0) return 0;
      const excellentCount = this.tableData.filter(item => {
        return item.score && item.score >= 85;
      }).length;
      return Math.round((excellentCount / this.tableData.length) * 100);
    },
    failRate() {
      if (!this.tableData || this.tableData.length === 0) return 0;
      const failCount = this.tableData.filter(item => {
        return item.score && item.score < 60;
      }).length;
      return Math.round((failCount / this.tableData.length) * 100);
    }
  },
  methods: {
    query() {
      api
        .getPageCount(this.queryForm.courseName, this.queryForm.studentName)
        .then(res => {
          this.pageCount = res;
          this.pageIndex = 1;
          this.getPage(1);
        });
    },
    getPage(pageIndex) {
      api
        .getPage(
          pageIndex,
          this.queryForm.courseName,
          this.queryForm.studentName
        )
        .then(res => {
          this.tableData = res;
        });
    },
    edit(id) {
      api.get(id).then(res => {
        this.entityForm = res;
        this.editing = true;
      });
    },
    save() {
      api.update(this.entityForm).then(() => {
        this.$message.success("成绩保存成功");
        this.getPage(this.pageIndex);
        this.editing = false;
      });
    },
    getSelectAndGradeStatus() {
      OptionApi.getAllowTeacherGrade().then(res => {
        this.isButtonDisabled = !res;
      });
    },
    getScoreClass(score) {
      if (!score) return 'score-none';
      if (score >= 85) return 'score-excellent';
      if (score >= 60) return 'score-pass';
      return 'score-fail';
    },
    getScoreTagType(score) {
      if (!score) return 'info';
      if (score >= 85) return 'success';
      if (score >= 60) return '';
      return 'danger';
    },
    calculateFinalScore() {
      const daily = parseFloat(this.entityForm.dailyScore) || 0;
      const exam = parseFloat(this.entityForm.examScore) || 0;
      // 计算总成绩：日常分占40%，笔试分占60%
      const finalScore = daily * 0.4 + exam * 0.6;
      this.entityForm.score = Math.round(finalScore);
    }
  },
  created() {
    this.query();
    this.getSelectAndGradeStatus();
  }
};
</script>

<style scoped>
.grade-wrap {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 100px);
}

.crumbs {
  margin-bottom: 20px;
}

/* 统计卡片样式 */
.statistics-area {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px 0 rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 10px;
  background-color: #409EFF;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.stat-icon i {
  font-size: 30px;
  color: #fff;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

/* 成绩管理容器 */
.grade-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.grade-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #EBEEF5;
}

.grade-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
  display: flex;
  align-items: center;
}

.grade-header h3 i {
  margin-right: 8px;
  color: #409EFF;
}

/* 查询表单 */
.query-form {
  margin-bottom: 20px;
}

.search-btn {
  width: 100%;
}

/* 表格样式 */
.grade-table {
  margin-bottom: 20px;
}

.score-excellent {
  color: #67C23A;
  font-weight: bold;
}

.score-pass {
  color: #409EFF;
}

.score-fail {
  color: #F56C6C;
}

.score-none {
  color: #909399;
}

/* 分页容器 */
.pagination-container {
  text-align: center;
  margin-top: 30px;
}

/* 编辑对话框 */
.grade-dialog {
  border-radius: 8px;
}

.dialog-content {
  padding: 0 20px;
}

.dialog-header {
  margin-bottom: 20px;
}

.course-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
  border-left: 4px solid #409EFF;
}

.course-info h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.course-info p {
  margin: 5px 0 0 0;
  color: #606266;
  font-size: 14px;
}

.score-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>
